<template>
  <div class="login">
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" label-position="left" label-width="0px" class="login-form">
      <h3 class="title">xxx Candidates System</h3>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码" @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
  import useUserStore from '@/store/modules/user'

  const userStore = useUserStore()
  const route = useRoute();
  const router = useRouter();
  const { proxy } = getCurrentInstance();

  const loginForm = ref({
    username: "",
    password: ""
  });

  const loginRules = {
    username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
    password: [{ required: true, trigger: "blur", message: "请输入您的密码" }]
  };

  const loading = ref(false);

  const redirect = ref(undefined);

  watch(route, (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  }, { immediate: true });

  function handleLogin() {
    proxy.$refs.loginRef.validate(valid => {
      if (valid) {
        loading.value = true;
        // 调用action的登录方法
        userStore.login(loginForm.value).then((response) => {
          loading.value = false
          if (response.statusCode === 200) {
            router.push({ path: "/index" });
          }
        }).catch((err) => {
          console.log(err)
          loading.value = false;
        });
      }
    });
  }
</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-color: #2d3a4b;
  background-size: cover;
}
.title {
  margin: 0 auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 385px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  display: inline-block;
  height: 38px;
}

.login-code img {
  cursor: pointer;
  vertical-align: middle;
}

</style>